package com.onlyxiahui.common.utils.base.io.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Description <br>
 * Date 2019-11-19 19:52:09<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class FileTextUtil {

	public static String getTextByFilePath(String filePath) {
		String text = null;
		InputStream input = null;
		BufferedReader in = null;
		try {
			File file = new File(filePath);
			if (file.exists() && file.isFile()) {
				StringBuilder sb = new StringBuilder();
				input = new FileInputStream(filePath);
				in = new BufferedReader(new InputStreamReader(input));
				String temp;
				boolean first = true;
				while ((temp = in.readLine()) != null) {
					if (!first) {
						sb.append("\n");
					} else {
						first = false;
					}
					sb.append(temp);
				}
				text = sb.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != input) {
					input.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return text;
	}

	/**
	 * 
	 * getTextByClassPath("/com/")<br>
	 *
	 * @date 2022-05-24 20:15:00<br>
	 * @param classPath
	 * @return
	 * @since 1.0.0
	 */
	public static String getTextByClassPath(String classPath) {
		String text = null;
		InputStream input = null;
		BufferedReader in = null;
		try {
			StringBuilder sb = new StringBuilder();
			input = FileTextUtil.class.getResourceAsStream(classPath);

			in = new BufferedReader(new InputStreamReader(input));
			String temp;
			boolean first = true;
			while ((temp = in.readLine()) != null) {
				if (!first) {
					sb.append("\n");
				} else {
					first = false;
				}
				sb.append(temp);
			}
			text = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != input) {
					input.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return text;
	}
}
